;+
; NAME: 
;       NOEXT 
;
; PURPOSE:
;
;	Read in a set of FITS files and write them out again with only a single FITS extension
;
; CATEGORY:
;	ASTRONOMY; DATA REDUCTION
;
; INPUTS:
;	
; OUTPUTS:
;
; KEYWORDS:
;
; REQUIRES:
;
; EXAMPLE:
;
;	IDL> noext
;         
; MODIFICATION HISTORY:
;
;	Written by KW - Dec 07
;-

pro noext, path=path

if not keyword_set(path) then path = '~/Astronomy/Research/APO/highz/Q4CU04/'

filenames = dialog_pickfile(/multiple_files, path = path, filter = '*fits', $
	title = 'FITS files (images) to be processed')
nimages = n_elements(filenames)

for i = 0, nimages - 1 do begin
	temp1 = readfits(filenames(i),hdr, exten_no = 0,/silent)
	extend_line = where(strmid(hdr,0,5) eq 'EXTEND')
	newname = strmid(filenames(i),0,strlen(filenames(i))-5)+'_noext.fits'

	if extend_line ne -1 then begin
;	if n_elements(extend_line) gt 1 then print,'Error reading FITS header'

		newhdr = [hdr(0:extend_line-1),hdr(extend_line+1:n_elements(hdr)-1)]
	
		extline2 = where(strmid(newhdr,0,6) eq 'EXTNAME')
		if sxpar('EXTNAME') ne 'MEAN_OF_DIFFERENCES' then print,'Wrong extension selected'
	
		newhdr2 = [newhdr(0:extline2-1),newhdr(extend_line+1:n_elements(newhdr)-1)]
		writefits, newname, temp1, newhdr2
	endif else writefits, newname, temp1, hdr
endfor

end
